package com.qiwenshare.file.aop;

import com.alibaba.fastjson2.JSONObject;
import com.qiwenshare.common.util.security.SessionUtil;
import com.qiwenshare.file.aop.annotation.FileOperationAuthCheck;
import com.qiwenshare.file.component.InitData;
import com.qiwenshare.file.constant.FileOperationTypeEnum;
import com.qiwenshare.file.constant.OperationTypeEnum;
import com.qiwenshare.file.util.JsonUtil;
import com.qiwenshare.file.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author MJ
 * @title qiwen-file
 * @date 2023/10/12 10:07
 * @description TODO
 */
@Aspect
@Component
@Slf4j
public class FileOperationAuthCheckAspect {
//    @Autowired
//    CheckAuthsService checkAuthsService;

    public FileOperationAuthCheckAspect() {
    }

    @Pointcut("@annotation(com.qiwenshare.file.aop.annotation.FileOperationAuthCheck)")
    public void cut() {
    }

    @Before("cut()")
    public void record(JoinPoint joinPoint) throws Exception {
        log.info("-----------------文件操作权限校验开始-----------------");
        String url = RequestUtil.getRequestUrl();
        String userId = SessionUtil.getUserId();
        String userFileId = "";
        log.info("校验URL：" + url);
        log.info("校验类型：" + getAuthAnnotation(joinPoint).operationType()[0].getDesc());
        log.info("校验用户：" + InitData.getStaffNameByUserId(userId) + "(" + userId + ")");

        // 请求参数
//        Object[] args = joinPoint.getArgs();
//        String jsonString = JsonUtil.toJsonString(args[0]);
//        JSONObject jsonObject = JSONObject.parseObject(jsonString);
//        userFileId = jsonObject.getString("userFileId");
//        log.info("校验文件ID：" + userFileId);







        log.info("-----------------文件操作权限校验结束-----------------");
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private FileOperationAuthCheck getAuthAnnotation(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(FileOperationAuthCheck.class);
        }
        return null;
    }
}
